package blog.open1111.controller;

import blog.open1111.entity.Article;
import blog.open1111.service.ArticleService;
import blog.open1111.util.OSSUtils;
import blog.open1111.util.ResponseUtil;
import blog.open1111.util.StringUtil;
import net.sf.json.JSON;
import net.sf.json.JSONObject;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Created by dengwubo on 2017/9/14.
 */
@Controller
@RequestMapping("/article")
public class ArticleController {




    @Autowired
    private ArticleService articleService;
    @RequestMapping("/{id}")
    public ModelAndView details(@PathVariable("id")Integer id, HttpServletRequest request) throws Exception{
        ModelAndView mav = new ModelAndView();
        Article article = articleService.findById(id);

        article.setClickHit(article.getClickHit()+1);
        articleService.update(article);
        String tags = article.getTags();
        if (StringUtil.isNotEmpty(tags)){
            String arr[]= tags.split(" ");
            mav.addObject("tags",StringUtil.filterWhite(Arrays.asList(arr)));
        }else{
            mav.addObject("tags",tags);
        }
        mav.addObject("article",article);
        mav.addObject("pageTitle",article.getTitle());
        mav.addObject("pageCode",getUpAndDownPageCode(articleService.getLastArticle(id),articleService.getNextArticle(id),request.getServletContext().getContextPath()));
        mav.addObject("magePage","foreground/article/view.jsp");
        mav.setViewName("mainTemp");
        return mav;
    }



    public String getUpAndDownPageCode(Article lastAricle,Article netArticle,String projectContext){
        StringBuilder pageCode = new StringBuilder();
        if (lastAricle==null||lastAricle.getId()==null){
            pageCode.append("<p>上一篇: 没有了</p>");
        }else{
            pageCode.append("<p>上一页: <a href='"+projectContext+"/article/"+lastAricle.getId()+".html'>"+lastAricle.getTitle()+"</p>");
        }

        if(netArticle==null || netArticle.getId()==null){
            pageCode.append("<p>下一篇：没有了</p>");
        }else{
            pageCode.append("<p>下一篇：<a href='"+projectContext+"/article/"+netArticle.getId()+".html'>"+netArticle.getTitle()+"</a></p>");
        }
        return pageCode.toString();

    }


    @RequestMapping(value = "/upload",produces = MediaType.APPLICATION_JSON_VALUE)
   // @ResponseBody
    public Map<String, Object> upload(MultipartFile upfile, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String,Object> params = new HashMap<String,Object>();
        JSONObject result = null;
        try{
            // 生成文件的key值
            String key = UUID.randomUUID().toString().replaceAll("-","");
            String ext =StringUtil.getExt(upfile.getOriginalFilename());

            String visitUrl = OSSUtils.uploadFile(key, upfile.getInputStream(),ext);
            System.out.println("visitUrl="+visitUrl);
            params.put("state","SUCCESS");
            params.put("url",visitUrl);
            params.put("size",upfile.getSize());
            params.put("original",key+"."+ext);
            params.put("type",upfile.getContentType());
             result= JSONObject.fromObject(params);


        }catch (Exception e){
            e.printStackTrace();
            params.put("state", "ERROR");
        }

        ResponseUtil.write(response,result);


    return null;
    }


}
